# -*- coding: utf-8 -*-

import os
import sys
from misc.net import is_valid_address, get_valid_address, is_valid_network, get_valid_network


def variable_is_network(value, version):
    if isinstance(value, str):
        if '-' in value:
            networks = value.split('-')
            for network in networks:
                if not is_valid_network(network, version):
                    return False
            else:
                return True
        else:
            return is_valid_network(value, version)
    elif isinstance(value, list):
        for item in value:
            if '-' in item:
                networks = item.split('-')
                for network in networks:
                    if not is_valid_network(network, version):
                        return False
            else:
                if not is_valid_network(item, version):
                    return False
        else:
            return True
    else:
        return False

def variable_is_ip(value, version):
    if isinstance(value, str):
        return is_valid_address(value, version)
    elif isinstance(value, list):
        for item in value:
            if not is_valid_address(item, version):
                return False
        else:
            return True
    else:
        return False

def check_variable_type(value, value_type):
    if isinstance(value_type, list):
        if value in value_type:
            return True
        else:
            return False
    elif isinstance(value_type, str):
        if value_type == "ip-4":
            return variable_is_ip(value, 4)
        elif value_type == "ip-6":
            return variable_is_ip(value, 6)
        elif value_type == "network-4":
            return variable_is_network(value, 4)
        elif value_type == "network-6":
            return variable_is_network(value, 6)
        elif value_type == "file":
            return os.path.isfile(value)
        else:
            if isinstance(value, eval(value_type)):
                return True
            else:
                return False
    else:
        return False

def check_value_is_empty(value):
    if isinstance(value, list):
        for item in value:
            if item:
                return False
        else:
            return True
    else:
        if value:
            return False
        else:
            return True

def check_list_is_empty(value):
    if isinstance(value, list):
        for item in value:
            if item:
                return False
        return True
    else:
        return False

def check_list_has_empty(value):
    if isinstance(value, list):
        for item in value:
            if not item:
                return True
        else:
            return False
    else:
        return False


def list_duplicate_removal(value):
    if isinstance(value, list):
        _ = lambda x, y: x if y in x else x + [y]
        return reduce(_, [[], ] + value)
    else:
        return None
